package com.cosmoplat.xikai.business.controller.agv;


import com.alibaba.fastjson2.JSONObject;
import com.cosmoplat.xikai.business.domain.AgvCallbackLog;
import com.cosmoplat.xikai.business.domain.dto.agv.AgvCallbackRequest;
import com.cosmoplat.xikai.business.domain.dto.agv.AgvCallbackResponse;
import com.cosmoplat.xikai.business.service.AgvService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName AgvCallController
 * @Description AGV回调控制器 处理AGV系统的请求
 * @Author wdf
 * @Date 2025/9/2
 */
@Slf4j
@RestController
@RequestMapping("/agv")
public class AgvCallController {

    @Autowired
    private AgvService agvService;

    /**
     * 处理AGV回调请求
     * 接口路径: /agvCallback
     * 请求方式: POST
     *
     * @param request AGV回调请求参数
     * @return 处理结果响应
     */
    @PostMapping("/agvCallback")
    public AgvCallbackResponse handleAgvCallback(@RequestBody AgvCallbackRequest request) {
        log.info("收到AGV回调请求，reqCode: {}, method: {}, taskCode: {}",
                request.getReqCode(), request.getMethod(), request.getTaskCode());

        // 根据请求中的method字段处理不同类型的回调
        try {
            // 创建日志记录
            AgvCallbackLog logRecord = agvService.getCallBackLog(request);
            switch(request.getMethod()) {
                case "apply":
                    // 处理AGV申请进入工作区的请求
                    agvService.processApplyRequest(logRecord);
                    // 运行agv 小车进入 回调agv的服务
                    agvService.asyncScheduleContinueTask(logRecord, request.getReqCode(), request.getTaskCode(), 1 * 1000);
                    break;
                case "release":
                    // 处理AGV申请离开工作区的请求
                    agvService.processReleaseRequest(logRecord, request);
                    break;
                default:
                    log.warn("未知的method类型: {}", request.getMethod());
                    return new AgvCallbackResponse("-1", "请求的方法方法名不存在" + request.getMethod(), request.getReqCode());
            }

            // 返回成功响应
            return new AgvCallbackResponse("0", "成功", request.getReqCode());
        } catch (Exception e) {
            log.error("处理AGV回调请求时发生异常，reqCode: {}", request.getReqCode(), e);
            return new AgvCallbackResponse("-1", "异常: " + e.getMessage(), request.getReqCode());
        }
    }
}
